<template>
  <div>
    <el-dialog
      :title="`${name}-下线列表`"
      v-model="other.isShow"
      lock-scroll
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      draggable
      align-center
      width="1000px"
      height="600px"
      @closed="closed"
    >
      <div class="agentsub-list-dialog-box">
        <div class="form mb-[10px]">
          <el-row :gutter="12">
            <el-col :span="4">
              <el-input v-model="form.Name" placeholder="用户名" />
            </el-col>
            <el-col :span="6">
              <div class="flex items-center">
                <el-button type="primary" @click.stop="search">搜索</el-button>
                <el-button type="danger" @click.stop="handleRefresh">清空</el-button>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="grow-[1] h-0 overflow-hidden">
          <el-table
            scrollbar-always-on
            ref="elTableRef"
            v-loading="state.loading"
            :data="list"
            style="width: 100%"
            height="100%"
            border
            stripe
            fit
          >
            <template #empty>
              <ui-empty />
            </template>
            <el-table-column align="center" prop="UserName" label="用户名" show-overflow-tooltip>
              <template #default="{ row }: TableItem">
                {{ row.UserName || "--" }}
              </template>
            </el-table-column>
            <el-table-column align="center" prop="NickName" label="昵称" show-overflow-tooltip>
              <template #default="{ row }: TableItem">
                {{ row.NickName || "--" }}
              </template>
            </el-table-column>
            <el-table-column align="center" prop="Coin" label="余额">
              <template #default="{ row }: TableItem">
                <ui-amount :num="row.Coin" />
              </template>
            </el-table-column>
            <el-table-column align="center" prop="AllWin" label="盈亏">
              <template #default="{ row }: TableItem">
                <ui-amount :num="row.AllWin" />
              </template>
            </el-table-column>
            <el-table-column align="center" prop="AllAmount" label="流水">
              <template #default="{ row }: TableItem">
                <ui-amount :num="row.AllAmount" />
              </template>
            </el-table-column>
            <el-table-column align="center" prop="AllAmount" label="回水比例">
              <template #default="{ row }: TableItem"> {{ row.BackWaterRate }} % </template>
            </el-table-column>
            <el-table-column align="center" prop="CommissionRate" label="抽佣比例">
              <template #default="{ row }: TableItem"> {{ row.CommissionRate }} % </template>
            </el-table-column>
            <el-table-column align="center" label="操作" aling="center" width="280">
              <template #default="{ row }: TableItem">
                <el-button type="success" size="small" @click="backUser(row)">回水比例</el-button>
                <el-button type="primary" size="small" @click="rateUser(row)">抽佣比例</el-button>
                <el-button type="danger" size="small" @click="cancelUser(row)">删除下线</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="flex justify-end mt-[10px] mx-[15px]">
          <ui-pagination
            :total="state.total"
            v-model:pageSize="state.pageSize"
            v-model:currentPage="state.page"
            @current-change="getData"
          ></ui-pagination>
        </div>
      </div>
    </el-dialog>
    <backwater-dialog
      ref="backwaterDialogRef"
      :uid="currentData?.UserId"
      :username="currentData?.UserName"
      @update="getData"
    />
    <commission-rate-dialog
      ref="commissionRateDialogRef"
      :uid="currentData?.UserId"
      :username="currentData?.UserName"
      @update="getData"
    />
  </div>
</template>
<script setup lang="ts">
import BackwaterDialog from "./backwater-dialog.vue";
import commissionRateDialog from "./commission-rate-dialog.vue";

import { reqAgentUserList, reqDelAgentUser } from "@/api/user";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { cloneDeep } from "lodash-es";
import { useList } from "@/hooks/useList";

interface TableItem {
  row: AgentUserMo;
}
interface Params {
  ParentId: number;
  Name?: string;
}
const props = withDefaults(
  defineProps<{
    name: string;
    pid: number | null;
  }>(),
  {
    name: "",
    pid: null
  }
);
const emit = defineEmits(["update"]);
const currentData = ref<AgentUserMo | null>(null);
const backwaterDialogRef = ref();
const commissionRateDialogRef = ref();
const other = reactive({
  isShow: false
});

const form = reactive({
  Name: ""
});

const getParams = () => {
  const params: Params = {
    ParentId: props.pid as number
  };
  if (form.Name) {
    params.Name = form.Name;
  }
  return params;
};

const { elTableRef, state, list, getData, search } = useList<AgentUserMo, Params>(
  reqAgentUserList,
  getParams
);

const closed = () => {
  other.isShow = false;
};
const open = () => {
  other.isShow = true;
  getData();
};

// 重置
const handleRefresh = () => {
  form.Name = "";
  search();
};

const backUser = (row: AgentUserMo) => {
  currentData.value = cloneDeep(row);
  nextTick(() => {
    backwaterDialogRef.value?.open();
  });
};

const rateUser = (row: AgentUserMo) => {
  currentData.value = cloneDeep(row);
  nextTick(() => {
    commissionRateDialogRef.value?.open();
  });
};

// 取消下线
const cancelUser = (row: AgentUserMo) => {
  ElMessageBox.confirm(`是否进行【取消代理】操作`, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          await reqDelAgentUser(row.UserId);
          instance.confirmButtonLoading = false;
          message.success("取消下线成功");
          getData();
          done();
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

defineExpose({
  open
});
</script>
<style scoped lang="scss">
.agentsub-list-dialog-box {
  width: 100%;
  height: 500px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
:deep(.el-table) td .cell {
  padding: 0px 5px !important;
}
</style>
